package com.youpai.platform.vulture.service.handler.event;

import com.alibaba.fastjson.JSONObject;
import com.youpai.platform.common.exceptions.RemoteException;
import com.youpai.platform.vulture.common.entity.AccessMessage;
import com.youpai.platform.vulture.common.enums.MsgFlagEnum;
import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.handler.vulture.MessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @date: 2022/7/10 18:23
 * @author: Anna
 * @version: 1.0
 * @description: 接收消息处理类
 */
@Slf4j
@Component
public class ReceiveMessageDispatchHandler implements MessageHandler {

    @Resource(name = "handShakeMessageHandler")
    private MessageHandler handShakeMessageHandler;
    @Resource(name = "heartbeatMessageHandler")
    private MessageHandler heartBeatMessageHandler;
    @Resource(name = "ordinaryMessageHandler")
    private MessageHandler ordinaryMessageHandler;

    @Override
    public void handle(VultureChannel vultureChannel, AccessMessage accessMessage) throws RemoteException {
        log.info("receive msg : {}", JSONObject.toJSONString(accessMessage));
        if (!MsgFlagEnum.isSupportFlag(accessMessage.getFlag())) {
            log.error("不支持的消息类型 - {}", accessMessage);
            throw new RemoteException(vultureChannel, "不支持的flag类型" + accessMessage.getFlag());
        }
        // 普通消息
        if (MsgFlagEnum.ORDINARY_MSG.flag == accessMessage.getFlag()) {
            // 校验通道是否可用
            checkChannelActive(vultureChannel);
            ordinaryMessageHandler.handle(vultureChannel, accessMessage);
        }
        // 心跳
        if (MsgFlagEnum.HEART_BEAT_PING.flag == accessMessage.getFlag() || MsgFlagEnum.HEART_BEAT_PONG.flag == accessMessage.getFlag()) {
            // 校验通道是否可用
            checkChannelActive(vultureChannel);
            heartBeatMessageHandler.handle(vultureChannel, accessMessage);
        }
        // 握手
        if (MsgFlagEnum.HAND_SHAKE.flag == accessMessage.getFlag()) {
            handShakeMessageHandler.handle(vultureChannel, accessMessage);
        }
    }

    private void checkChannelActive(VultureChannel vultureChannel) throws RemoteException {
        if (!vultureChannel.isActive()) {
            throw new RemoteException(vultureChannel, "通道没有激活！");
        }
    }

}
